﻿using System.Security.Cryptography;
using System.Text;

namespace LB.Common
{
    public class PasswordEncryptor
    {
        public static string GetStringHesh(string plaintextPassword)
        {
            var byteHesh = GetHesh(plaintextPassword);
            return ToString(byteHesh);
        }

        public  static byte[] GetHesh(string plaintextPassword)
        {
            UnicodeEncoding encoding = new UnicodeEncoding();
            byte[] passwordBytes = encoding.GetBytes(plaintextPassword.ToString());

            SHA256 shaM = new SHA256Managed();
            return shaM.ComputeHash(passwordBytes);
        }

        public static byte[] RecreateFromHashedAscii(string hashedAscii)
        {
            var newHash = new byte[(hashedAscii.Length / 2)];
            for (var i = 0; i < (hashedAscii.Length / 2); i++)
            {
                newHash[i] = byte.Parse(hashedAscii.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture);
            }
            return newHash;
        }

        public static string ToString(byte[] passwordHash)
        {
            var output = new StringBuilder();

            foreach (var b in passwordHash)
            {
                output.Append(b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture));
            }

            return output.ToString();
        }	
    }
}
